package viz.plugin.bank.ocr

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.etop.BankCard.BankCardAPI
import com.etop.BankCard.BankCardInfoAPI
import com.etop.bank.activity.BankScanActivity
import com.etop.bank.model.OcrKeyDatas
import com.etop.bank.utils.BankConfig
import com.etop.bank.utils.NV21ToARGBUtil
import com.etop.bank.utils.StreamUtil
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry
import java.io.File
import java.util.regex.Pattern

/**
 * @title: BankOcrDelegate
 * @projectName android
 * @description:
 * @author zhangwei
 * @date 2020/11/24 14:17
 */

class BankOcrDelegate(
        private val activity: Activity,
        private var pendingResult: MethodChannel.Result? = null,
        private var methodCall: MethodCall? = null
) : PluginRegistry.ActivityResultListener {
    // 核心对象
    private var bankApi: BankCardAPI? = null
    private var cardinfoapi: BankCardInfoAPI? = null
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        when (requestCode) {
            101 -> {
                data?.apply {
                    // TODO HashMap格式数据
                    val hashMap: HashMap<String, String> = getSerializableExtra(OcrKeyDatas.RECOG_RESULT_HASHMAP) as HashMap<String, String>
                    //  获取识别码
                    val recogCode = data.getIntExtra(OcrKeyDatas.RECOG_CODE, -1)
                    //接收识别的裁切图路径
                    val bankPath = data.getStringExtra(OcrKeyDatas.CROP_PATH)
                    //接收识别框内图路径
                    val imagePath = data.getStringExtra(OcrKeyDatas.IMAGE_PATH)

                    // 添加结果结合
                    val resultMap = mutableMapOf<String, Any>()
                    if (recogCode == 0) {
                        resultMap["success"] = true
                        resultMap["number"] = hashMap["bankNum"] ?: ""
                        resultMap["type"] = hashMap["bankType"] ?: ""
                        resultMap["issuer"] = hashMap["bankName"] ?: ""
                        resultMap["bankCardName"] = hashMap["bankCardName"] ?: ""
                        resultMap["bankCode"] = hashMap["bankCode"] ?: ""
                        resultMap["originalImagePath"] = imagePath
                        resultMap["numberImagePath"] = bankPath
                        pendingResult?.success(resultMap.toMap())
                        clearMethodCallAndResult()
                    } else {
                        resultMap["success"] = false
                        resultMap["message"] = hashMap["ocrError"] ?: ""
                        pendingResult?.error("-1", hashMap["ocrError"], resultMap.toMap())
                        clearMethodCallAndResult()
                    }
                }
            }
        }
        return true
    }

    fun ocr() {
        //Android 6.0以上版本，权限适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //检查是否有相应的权限
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                val intent = Intent(activity, BankScanActivity::class.java)
                intent.putExtra(OcrKeyDatas.RECOG_TYPE, false)
                activity.startActivityForResult(intent, 101)
            } else {
                //没有权限申请权限
                ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE), 102)
            }
        } else {
            val intent = Intent(activity, BankScanActivity::class.java)
            intent.putExtra(OcrKeyDatas.RECOG_TYPE, false)
            activity.startActivityForResult(intent, 101)
        }
    }

    /**
     * 初始化OCR核心
     */
    fun initOCR() {
        /** 进入扫描页面前必须加上，否则识别核心激活失败，返回错误码21，无法识别  */
        StreamUtil.initLicenseFile(activity, BankConfig.licenseId)
        StreamUtil.initNCFile(activity, BankConfig.nc_obj_bin)
        StreamUtil.initNCFile(activity, BankConfig.nc_obj_param)
        StreamUtil.initNCFile(activity, BankConfig.bc_nc_bin)
        StreamUtil.initNCFile(activity, BankConfig.bc_nc_dic)
        StreamUtil.initNCFile(activity, BankConfig.bc_nc_param)
        pendingResult?.success(true)
        clearMethodCallAndResult()
    }

    fun bankOcrFromImagePath(imagePath: String) {
        val recogval = CharArray(30)
        bankApi = BankCardAPI.getBankInstance()
        val initKernalCode: Int = bankApi!!.initBankKernal(activity)
        if (initKernalCode == 0) {
            if (cardinfoapi == null) {
                cardinfoapi = BankCardInfoAPI()
                cardinfoapi?.InitCardInfo()
            }
            val endTime: String = bankApi!!.GetEndTime()
            Log.e("BankScanActivity", "授权截止日期 ------------- $endTime")
        } else {
            pendingResult?.error("""
    OCR核心激活失败:$initKernalCode
    错误信息：${BankConfig.getErrorInfo(initKernalCode)}
    """.trimIndent(), null, null)
            clearMethodCallAndResult()
            return
        }
        val recogCode = bankApi?.ScanImage(imagePath, recogval)
        if (recogCode == 0) {
            val cardinfo = arrayOfNulls<String>(4)
            //调用获取识别结果接口获取识别结果
            cardinfoapi!!.GetCardInfo(recogval, cardinfo)
            //获取银行卡号
            val str = String(recogval)
            val regEx = "[^0-9]"
            val p = Pattern.compile(regEx)
            val m = p.matcher(str)
            val bankNumber = m.replaceAll("").trim { it <= ' ' }
            //获取银行名称
            val bankName = cardinfo[0]
            //获取银行代码
            val bankCode = cardinfo[1]
            //获取卡名称
            val cardName = cardinfo[2]
            //获取卡类型
            val cardType = cardinfo[3]
            //            Log.e("识别成功", "bankNumber:" + bankNumber + ",bankName:" + bankName + ",bankCode:" + bankCode
//                    + ",cardName:" + cardName + ",cardType:" + cardType);
            val resultMap = mutableMapOf<String, String>()
            //将识别完成后，获取识别结果，添加到集合中
            resultMap[OcrKeyDatas.BANK_KEY[0]] = bankNumber
            resultMap[OcrKeyDatas.BANK_KEY[1]] = bankName?:""
            resultMap[OcrKeyDatas.BANK_KEY[2]] = cardName?:""
            resultMap[OcrKeyDatas.BANK_KEY[3]] = bankCode?:""
            resultMap[OcrKeyDatas.BANK_KEY[4]] = cardType?:""
            pendingResult?.success(resultMap.toMap())
            clearMethodCallAndResult()
        } else {
            val resultMap = mutableMapOf<String, Any>()
            resultMap["success"] = false
            resultMap["message"] = "识别识别"
            pendingResult?.error("-2", resultMap["message"].toString(), resultMap.toMap())
            clearMethodCallAndResult()
        }
    }

    private fun clearMethodCallAndResult() {
        methodCall = null
        pendingResult = null
    }
}